package cn.aws360.boot.data.api.factory;

import cn.aws360.boot.data.api.pojo.request.PageQuery;
import cn.aws360.boot.data.api.pojo.response.PageResult;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.PageUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import org.springframework.data.domain.Sort;


/**
 * @author junnan
 */
public class PageFactory {

    public static <T> Page<T> getPage(PageQuery pageQuery) {
        Page<T> page = new Page<>();
        page.setSize(Convert.toInt(pageQuery.getPageSize()));
        page.setCurrent(Convert.toInt(pageQuery.getPageNum()));
        String orderBy = pageQuery.getOrderBy();
        if (StrUtil.isNotBlank(orderBy)) {
            orderBy = StrUtil.toUnderlineCase(orderBy);
            boolean orderIsAsc = pageQuery.getOrderDir().equalsIgnoreCase(Sort.Direction.ASC.name());
            page.setOrders(orderIsAsc ? OrderItem.ascs(orderBy) : OrderItem.descs(orderBy));
        }
        return page;
    }

    public static <T> PageResult<T> getPageResult(Page<T> page) {
        PageResult<T> pageResult = new PageResult<>();
        pageResult.setRows(page.getRecords());
        pageResult.setTotalRows(Convert.toInt(page.getTotal()));
        pageResult.setPageNum(Convert.toInt(page.getCurrent()));
        pageResult.setPageSize(Convert.toInt(page.getSize()));
        pageResult.setTotalPage(PageUtil.totalPage(pageResult.getTotalRows(), pageResult.getPageSize()));
        return pageResult;
    }

    public static <T> PageResult<T> getPageResult(IService<T> service, PageQuery pageQuery, LambdaQueryWrapper<T> wrapper) {
        return getPageResult(service.page(getPage(pageQuery), wrapper));
    }

}
